const setupErrorHandle = () => {
    // 统一错误处理
    // 1.导入app
    const app = require("./../app");
    const {
        NAME_OR_PASSWORD_IS_REQUIRED,
        NAME_IS_ALREADY_EXISTS,
        NAME_IS_NOT_EXIST,
        PASSWORD_IS_INCORRECT,
        UNAUTHORIZATION,
        PERMISSION_IS_NOT_ALLOWED,
        RESOURCE_IS_NOT_EXISTS,
        UNKNOWN_ERROR,
        IS_MISSING_REQUIRED_PARAMETER,
    } = require("../config/error-constants");

    // 2.开启监听
    app.on("error", (error, ctx) => {
        let code = 0;
        let message = "";
        switch (error) {
            case NAME_OR_PASSWORD_IS_REQUIRED:
                code = -1001;
                message = "用户名或者密码不能为空~";
                break;
            case NAME_IS_ALREADY_EXISTS:
                code = -1002;
                message = "用户名已经被占用，请尝试其他用户名~";
                break;
            case NAME_IS_NOT_EXIST:
                code = -1003;
                message = "登录的用户名不存在，请检查用户名~";
                break;
            case PASSWORD_IS_INCORRECT:
                code = -1004;
                message = "输入密码错误，请检查用户密码~";
                break;
            case UNAUTHORIZATION:
                code = -1005;
                message = "token无效或者token过期~";
                break;
            case PERMISSION_IS_NOT_ALLOWED:
                code = -2001;
                message = "没有操作资源权限~";
                break;
            case RESOURCE_IS_NOT_EXISTS:
                code = -2002;
                message = "对应资源不存在~";
                break;
            case IS_MISSING_REQUIRED_PARAMETER:
                code = -3333;
                message = "必要参数肯能未传递~";
                break;
            case UNKNOWN_ERROR:
                code = -9999;
                message = "未知原因错误，请联系管理员~";
                break;
        }

        ctx.body = {
            code,
            message,
        };
    });
};


module.exports = setupErrorHandle;